import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:math';

class SharedPre extends StatefulWidget {
  final String title;

  SharedPre({Key key, this.title}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return SharedPreState();
  }
}

class SharedPreState extends State<SharedPre> {
  final String keyName = 'key';
  var val = '';

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        children: <Widget>[
          RaisedButton(
            onPressed: () {
              _saveSP('存储数据:${Random().nextInt(1000)}');
            },
            child: Text('shared_preferences 存储'),
          ),
          RaisedButton(
            onPressed: () {
              _getSP(keyName);
            },
            child: Text('shared_preferences 获取'),
          ),
          Text(val)
        ],
      ),
    );
  }

  void _saveSP(String s) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    await sp.setString(keyName, s);
  }

  void _getSP(String keyName) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    String value = sp.getString(keyName);
    setState(() {
      this.val = value;
    });
  }
}
